<?php

namespace app\api\controller;

use app\common\service\CompanyService;
use app\common\service\EmissionService;
use think\Db;

class Company extends BaseController
{

    /**
     * 公司接口信息
     * @throws \Exception
     * @author hongwei 2019-05-31
     */
    public function getCompanyList()
    {
        //step1:公司的基本信息
        $sql  = 'select * from basic_company where delete_time=0 order by id asc';
        $data = Db::query($sql);
        //step2:排口的基本信息
        foreach ($data as $k => $v) {
            $data[$k]['drain']    = Db::query('select * from basic_drain where company_id = ' . $v['id']);
            $data[$k]['facility'] = Db::query('select * from basic_facility where company_id = ' . $v['id']);
        }
        if (!$data) {
            throw new \Exception('获取公司列表的接口失败！');
        }
        $this->success('获取公司信息成功', $data);
    }

    /**
     * 获取行业列表
     * @throws \Exception
     * @author hongwei 2019-05-31
     */
    public function getIndustryList()
    {
        $sql  = 'select * from basic_industry  where delete_time=0 order by id asc';
        $data = Db::query($sql);
        if (!$data) {
            throw new \Exception('获取行业信息的接口失败！');
        }
        $this->success('获取行业信息成功', $data);
    }

    /**
     * 站点列表接口
     * @throws \Exception
     * @author hongwei 2019-05-31
     */
    public function getStationList()
    {
        $sql  = 'select * from basic_station where station_id <> 0 order by id asc';
        $data = Db::query($sql);
        if (!$data) {
            throw new \Exception('获取站点列表接口失败！');
        }
        $this->success('获取站点列表接口成功！', $data);
    }

    /**
     * 获取NC数据的基本配置信息
     * @author hongwei 2019-06-03
     */
    public function getNcInfo()
    {
        $sql  = 'select name_en,name_zh,value from system_setting where type = "nc" order by id asc';
        $data = Db::query($sql);
        if (!$data) {
            throw new \Exception('获取NC数据的基本配置信息失败！');
        }
        $this->success('获取NC数据的基本配置成功！', $data);
    }

    /**
     * 源清单经纬度基本信息接口
     * @throws \Exception
     * @author hongwei 2019-06-04
     */
    public function getSourceListInfo()
    {
        $sql  = 'select name_en,name_zh,value from system_setting where type = "source" order by id asc';
        $data = Db::query($sql);
        if (!$data) {
            throw new \Exception('获取源清单经纬度基本信息失败！');
        }
        $this->success('获取源清单经纬度基本信息成功！', $data);
    }

    /**
     * 接口06：工业基本情况接口-获取
     * @author hongwei 2019-07-03
     */
    public function companyIndustry()
    {
        //step1:传参
        $param = $this->request->param();
        if (empty($param['start_date'])) {
            $this->error('参数错误');
        }
        $startDay = $param['start_date']; //开始日期，往前推7天

        //step2:获取
        $emission = new EmissionService();
        $data     = [];
        if (isset($param['company_id'])) {
            $companyId = $param['company_id'];
            $data[]      = $emission->getSingleCompanyAndDrainEmissionMinToHourAvg($companyId, $startDay);
            $data[0]['drain'] = array_values($data[0]['drain']);
        } else {
            $company     = new CompanyService();
            $companyList = $company->getAllCompany();
            foreach ($companyList as $k => $v) {
                $data[$k] = $emission->getSingleCompanyAndDrainEmissionMinToHourAvg($v['id'], $startDay);
                $data[$k]['drain'] = array_values($data[$k]['drain']);
            }
        }
        if (!$data) {
            $this->error('获取数据失败！');
        }
        $this->success('获取数据成功！', $data);
    }

    /**
     * 接口06：工业基本情况接口-获取
     * @author lvkai 2019-06
     * @author hongwei 2019-06-14 换算单位，发现烟尘的BUG，保留小数
     */
//    public function companyIndustry()
//    {
//        $param = $this->request->param();
//        if (empty($param['start_date'])) {
//            $this->error('参数错误');
//        }
//
//        $where  = "";
//        $where1 = "";
//        if (!empty($param['company_id'])) {
//            $where  .= " AND company_id = {$param['company_id']} ";
//            $where1 .= " WHERE company_id = {$param['company_id']} ";
//        }
//        $expire_time = 72;
//        $end_date    = date('Y-m-d H:i:s', strtotime("$param[start_date] +$expire_time hour"));
//
//
//        $sql1  = "SELECT c.publish_time,c.company_id,c.company_name,c.drain_id,c.drain_name,sum(c.emissions) as nox_emissions FROM `company_industry_monitor_nitre_hour` as c WHERE (publish_time between '{$param['start_date']}' AND  '{$end_date}')$where GROUP BY `company_id`,`publish_time`,`drain_id`";
//        $sql2  = "SELECT c.publish_time,c.company_id,c.company_name,sum(c.emissions) as nox_emissions FROM `company_industry_monitor_nitre_hour` as c WHERE (publish_time between '{$param['start_date']}' AND  '{$end_date}')$where GROUP BY `company_id`,`publish_time`";
//        $sql3  = "SELECT publish_time,company_id,company_name,drain_id,drain_name,sum(emissions) as so2_emissions,sum(export_smoke_dust) as tsp_emissions FROM `company_industry_monitor_sulfur_hour`  WHERE (publish_time between '{$param['start_date']}' AND  '{$end_date}')$where GROUP BY `company_id`,`publish_time`,`drain_id`";
//        $sql4  = "SELECT publish_time,company_id,company_name,sum(emissions) as so2_emissions,sum(export_smoke_dust) as tsp_emissions FROM `company_industry_monitor_sulfur_hour`  WHERE (publish_time between '{$param['start_date']}' AND  '{$end_date}')$where GROUP BY `company_id`,`publish_time`";
//        $sql5  = "SELECT * FROM ({$sql1}) as a inner join ({$sql3}) as b on a.publish_time=b.publish_time and a.company_id=b.company_id";
//        $sql6  = "SELECT * FROM ({$sql2}) as a inner join ({$sql4}) as b on a.publish_time=b.publish_time and a.company_id=b.company_id";
//        $data1 = Db::query($sql5);
//        $data2 = Db::query($sql6);
//
//        $sql7  = "SELECT publish_hour,company_id,company_name,drain_name,emissions_so2 AS so2_emissions,emissions_nox AS nox_emissions,emissions_smoke as tsp_emissions FROM `company_industry_monitor_simulation_hour_avg`$where1";
//        $sql8  = "SELECT publish_hour,company_id,company_name,emissions_so2 AS so2_emissions,emissions_nox AS nox_emissions,emissions_smoke as tsp_emissions FROM `company_industry_monitor_simulation_hour_avg`$where1 GROUP BY `company_id`,`publish_hour`";
//        $data3 = Db::query($sql7);
//        $data5 = Db::query($sql8);
//
//        $dates  = self::getDateFromRange($param['start_date'], $end_date);
//        $startH = date('H', strtotime($param['start_date']));
//        $endH   = date('H', strtotime($end_date));
//        $date   = [];
//        foreach ($dates['dates'] as $k => $v) {
//            for ($i = 0; $i < 24; $i++) {
//                if (($k == 0 && $i < $startH) || ($k == (count($dates['dates']) - 1) && $i > $endH)) {
//                    continue;
//                }
//                $date[] = date("Y-m-d $i:00:00", strtotime($v));
//            }
//        }
//        $_data3 = [];
//        $_data5 = [];
//        foreach ($data3 as $k => $v) {
//            $v['publish_time'] = $v['publish_hour'];
//            unset($v['publish_hour']);
//            foreach ($date as $key => $value) {
//                if (date('H:00:00', strtotime($v['publish_time'])) == date('H:00:00', strtotime($value))) {
//                    $v['publish_time'] = $value;
//                    $_data3[]          = $v;
//                }
//            }
//        }
//        foreach ($data5 as $k => $v) {
//            $v['publish_time'] = $v['publish_hour'];
//            unset($v['publish_hour']);
//            foreach ($date as $key => $value) {
//                if (date('H:00:00', strtotime($v['publish_time'])) === date('H:00:00', strtotime($value))) {
//                    $v['publish_time'] = $value;
//                    $_data5[]          = $v;
//                }
//            }
//        }
//
//        $data2 = array_merge($data2, $_data5);
//        $data1 = array_merge($data1, $_data3);
//
//        $data = [];
//        foreach ($data2 as $key => $value) {
//            $data[$key] = [
//                'id'           => $value['company_id'],
//                'company_name' => $value['company_name'],
//                'start_time'   => $value['publish_time'],
//                'expire_time'  => $expire_time,
//                'company'      => [
//                    "so2_emissions" => round($value['so2_emissions'] / 1000000, 6), //转换为kg/h,原来为mg/h
//                    "nox_emissions" => round($value['nox_emissions'] / 1000000, 6),
//                    "tsp_emissions" => round($value['tsp_emissions'] / 1000000, 6),
//                ]
//            ];
//            foreach ($data1 as $k => $v) {
//
//                if ($value['company_id'] . '_' . $v['publish_time'] === $value['company_id'] . '_' . $value['publish_time']) {
//                    $data[$key]['drain'] = [
//                        'name'          => $v['drain_name'],
//                        "so2_emissions" => round($v['so2_emissions'] / 1000000, 6),
//                        "nox_emissions" => round($v['nox_emissions'] / 1000000, 6),
//                        "tsp_emissions" => round($v['tsp_emissions'] / 1000000, 6),
//                    ];
//                }
//            }
//        }
//        $this->success('获取工业企业的基本信息成功', $data);
//    }

    /**
     * 获取指定日期段内每一天的日期和天数
     * @param string $startDate 开始日期 格式化时间 Y-m-d H:i:s
     * @param string $endDate 结束日期 格式化时间 Y-m-d H:i:s
     * @return array
     */
    public static function getDateFromRange($startDate, $endDate)
    {
        $startDate  = date('Y-m-d 00:00:00', strtotime($startDate));
        $endDate    = date('Y-m-d 23:59:59', strtotime($endDate));
        $sTimestamp = strtotime($startDate);
        $eTimestamp = strtotime($endDate);
        if ($eTimestamp < $sTimestamp) return [];
        // 计算日期段内有多少天
        $days = (int)ceil(($eTimestamp - $sTimestamp) / 86400);
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Y-m-d', $sTimestamp + (86400 * $i));
        }
        $data = [
            'dates' => $date,
            'days'  => $days,
        ];
        return $data;
    }

    /**
     * 公司源清单网格行和列
     * @author hongwei 2019-06-26
     */
    public function getCompanyNrowNcol()
    {
        $field = 'id,name,nrow,ncol';
        $sql   = 'select ' . $field . ' from basic_company where delete_time=0 order by id asc';
        $data  = Db::query($sql);
        if (!$data) {
            $this->error('获取公司源清单网格行和列失败！');
        }
        $this->success('获取公司源清单网格行和列成功！', $data);

    }
}